
#ifndef DVERSIONNUMBER_H
#define DVERSIONNUMBER_H

#include "devcommon_global.h"

#include <QtCore/qnamespace.h>
#include <QtCore/qstring.h>
#include <QtCore/qvector.h>
#include <QtCore/qmetatype.h>
//#include <QtCore/qtypeinfo.h>


class DVersionNumber
{
    /*
     * QVersionNumber stores small values inline, without memory allocation.
     * We do that by setting the LSB in the pointer that would otherwise hold
     * the longer form of the segments.
     * The constants below help us deal with the permutations for 32- and 64-bit,
     * little- and big-endian architectures.
     */
    enum {
        // in little-endian, inline_segments[0] is shared with the pointer's LSB, while
        // in big-endian, it's inline_segments[7]
        InlineSegmentMarker = Q_BYTE_ORDER == Q_LITTLE_ENDIAN ? 0 : sizeof(void*) - 1,
        InlineSegmentStartIdx = !InlineSegmentMarker, // 0 for BE, 1 for LE
        InlineSegmentCount = sizeof(void*) - 1
    };
//    Q_STATIC_ASSERT(InlineSegmentCount >= 3);   // at least major, minor, micro

    struct SegmentStorage {
        // Note: we alias the use of dummy and inline_segments in the use of the
        // union below. This is undefined behavior in C++98, but most compilers implement
        // the C++11 behavior. The one known exception is older versions of Sun Studio.
        union {
            quintptr dummy;
            qint8 inline_segments[sizeof(void*)];
            QVector<int> *pointer_segments;
        };

        // set the InlineSegmentMarker and set length to zero
        SegmentStorage() : dummy(1) {}

        SegmentStorage(const QVector<int> &seg)
        {
            if (dataFitsInline(seg.begin(), seg.size()))
                setInlineData(seg.begin(), seg.size());
            else
                pointer_segments = new QVector<int>(seg);
        }

        SegmentStorage(const SegmentStorage &other)
        {
            if (other.isUsingPointer())
                pointer_segments = new QVector<int>(*other.pointer_segments);
            else
                dummy = other.dummy;
        }

        SegmentStorage &operator=(const SegmentStorage &other)
        {
            if (isUsingPointer() && other.isUsingPointer()) {
                *pointer_segments = *other.pointer_segments;
            } else if (other.isUsingPointer()) {
                pointer_segments = new QVector<int>(*other.pointer_segments);
            } else {
                if (isUsingPointer())
                    delete pointer_segments;
                dummy = other.dummy;
            }
            return *this;
        }

#ifdef Q_COMPILER_RVALUE_REFS
        SegmentStorage(SegmentStorage &&other)
            : dummy(other.dummy)
        {
            other.dummy = 1;
        }

        SegmentStorage &operator=(SegmentStorage &&other)
        {
            qSwap(dummy, other.dummy);
            return *this;
        }

        explicit SegmentStorage(QVector<int> &&seg)
        {
            if (dataFitsInline(seg.begin(), seg.size()))
                setInlineData(seg.begin(), seg.size());
            else
                pointer_segments = new QVector<int>(std::move(seg));
        }
#endif
#ifdef Q_COMPILER_INITIALIZER_LISTS
        SegmentStorage(std::initializer_list<int> args)
        {
            if (dataFitsInline(args.begin(), int(args.size()))) {
                setInlineData(args.begin(), int(args.size()));
            } else {
                pointer_segments = new QVector<int>(args);
            }
        }
#endif

        ~SegmentStorage() { if (isUsingPointer()) delete pointer_segments; }

        bool isUsingPointer() const
        { return (inline_segments[InlineSegmentMarker] & 1) == 0; }

        int size() const
        { return isUsingPointer() ? pointer_segments->size() : (inline_segments[InlineSegmentMarker] >> 1); }

        void setInlineSize(int len)
        { inline_segments[InlineSegmentMarker] = 1 + 2 * len; }

        void resize(int len)
        {
            if (isUsingPointer())
                pointer_segments->resize(len);
            else
                setInlineSize(len);
        }

        int at(int index) const
        {
            return isUsingPointer() ?
                        pointer_segments->at(index) :
                        inline_segments[InlineSegmentStartIdx + index];
        }

        void setSegments(int len, int maj, int min = 0, int mic = 0)
        {
            if (maj == qint8(maj) && min == qint8(min) && mic == qint8(mic)) {
                int data[] = { maj, min, mic };
                setInlineData(data, len);
            } else {
                setVector(len, maj, min, mic);
            }
        }

    private:
        static bool dataFitsInline(const int *data, int len)
        {
            if (len > InlineSegmentCount)
                return false;
            for (int i = 0; i < len; ++i)
                if (data[i] != qint8(data[i]))
                    return false;
            return true;
        }
        void setInlineData(const int *data, int len)
        {
            dummy = 1 + len * 2;
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
            for (int i = 0; i < len; ++i)
                dummy |= quintptr(data[i] & 0xFF) << (8 * (i + 1));
#elif Q_BYTE_ORDER == Q_BIG_ENDIAN
            for (int i = 0; i < len; ++i)
                dummy |= quintptr(data[i] & 0xFF) << (8 * (sizeof(void *) - i - 1));
#else
            // the code above is equivalent to:
            setInlineSize(len);
            for (int i = 0; i < len; ++i)
                inline_segments[InlineSegmentStartIdx + i] = data[i] & 0xFF;
#endif
        }

        Q_CORE_EXPORT void setVector(int len, int maj, int min, int mic);
    } m_segments;

public:
    inline DVersionNumber()
        : m_segments()
    {}
    inline explicit DVersionNumber(const QVector<int> &seg)
        : m_segments(seg)
    {}

    // compiler-generated copy/move ctor/assignment operators and the destructor are ok

#ifdef Q_COMPILER_RVALUE_REFS
    explicit DVersionNumber(QVector<int> &&seg)
        : m_segments(std::move(seg))
    {}
#endif

#ifdef Q_COMPILER_INITIALIZER_LISTS
    inline DVersionNumber(std::initializer_list<int> args)
        : m_segments(args)
    {}
#endif

    inline explicit DVersionNumber(int maj)
    { m_segments.setSegments(1, maj); }

    inline explicit DVersionNumber(int maj, int min)
    { m_segments.setSegments(2, maj, min); }

    inline explicit DVersionNumber(int maj, int min, int mic)
    { m_segments.setSegments(3, maj, min, mic); }

    inline bool isNull() const
    { return segmentCount() == 0; }

    inline bool isNormalized() const
    { return isNull() || segmentAt(segmentCount() - 1) != 0; }

    inline int majorVersion() const
    { return segmentAt(0); }

    inline int minorVersion() const
    { return segmentAt(1); }

    inline int microVersion() const
    { return segmentAt(2); }

    DVersionNumber normalized() const;

    QVector<int> segments() const;

    inline int segmentAt(int index) const
    { return (m_segments.size() > index) ? m_segments.at(index) : 0; }

    inline int segmentCount() const
    { return m_segments.size(); }

    bool isPrefixOf(const DVersionNumber &other) const;

    static int compare(const DVersionNumber &v1, const DVersionNumber &v2);

    static DVersionNumber commonPrefix(const DVersionNumber &v1, const DVersionNumber &v2);

    QString toString() const;
#if QT_STRINGVIEW_LEVEL < 2
    static DVersionNumber fromString(const QString &string, int *suffixIndex = nullptr);
#endif
    static DVersionNumber fromString(QByteArray string, int *suffixIndex = nullptr);

private:
#ifndef QT_NO_DATASTREAM
    friend Q_CORE_EXPORT QDataStream& operator>>(QDataStream &in, DVersionNumber &version);
#endif

};

Q_DECLARE_TYPEINFO(DVersionNumber, Q_MOVABLE_TYPE);

#ifndef QT_NO_DEBUG_STREAM
DEVCOMMONSHARED_EXPORT QDebug operator<<(QDebug, const DVersionNumber &version);
#endif

DEVCOMMONSHARED_EXPORT inline bool operator> (const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) > 0; }

DEVCOMMONSHARED_EXPORT inline bool operator>=(const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) >= 0; }

DEVCOMMONSHARED_EXPORT inline bool operator< (const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) < 0; }

DEVCOMMONSHARED_EXPORT inline bool operator<=(const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) <= 0; }

DEVCOMMONSHARED_EXPORT inline bool operator==(const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) == 0; }

DEVCOMMONSHARED_EXPORT inline bool operator!=(const DVersionNumber &lhs, const DVersionNumber &rhs)
{ return DVersionNumber::compare(lhs, rhs) != 0; }


Q_DECLARE_METATYPE(DVersionNumber)

#endif //DVERSIONNUMBER_H
